import axios from 'axios'
import qs from 'qs'
import { ElLoading, ElMessage } from 'element-plus'
// import Cookies from 'js-cookie'
const { basePath } = require('../../../faceConfig.js')
// const token = Cookies.get('XSRF-TOKEN')

const Axios = axios.create({
  baseURL: basePath,
  timeout: 1000 * 10,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    // "Content-Type": "application/json;charset=UTF-8",
    // 'X-XSRF-TOKEN': token
  },
})

class Http {
  constructor() {
    this.fileMage = '请求发生错误'
  }
  //将后台返回的 null 转化为 ""
  /* function isNull(val) {
    if (val === null) {
      return "";
    } else if (val.constructor === Object || val.constructor === Array) {
      for (let k in val) {
        val[k] = isNull(val[k]);
      }
    }
    return val;
  } */
  post(params) {
    return this.submit({
      method: 'post',
      ...params,
    })
  }
  get(params) {
    return this.submit({
      method: 'get',
      ...params,
    })
  }
  /**
   *
   * @param {autoFileMag} 在请求失败时，是否自动提示message 默认为 true
   * @param {isJson}  请求为 post时，是否传输 json 格式， 默认 urlencoded 格式
   * @param {isFile}  请求为 post时，传输数据中包含文件类型 转为formdata
   * @param {isLoading} 发送请求时，是否需要 Loading 效果
   * @returns Promise 接口返回结果
   */
  submit({ url, method, data = {}, autoFileMag = true, isJson = false, isLoading = true, isFile = false, ...config }) {
    // 参数整理
    let requestData = {}
    if (method === 'get') {
      requestData.params = data
    } else if (isJson) {
      requestData.data = data
      config.headers
        ? (config.headers['Content-Type'] = 'application/json;charset=UTF-8')
        : (config.headers = {
            'Content-Type': 'application/json;charset=UTF-8',
          })
    } else {
      requestData.data = qs.stringify(data)
    }
    // 包含文件格式
    if (isFile) {
      let formdata = new FormData()
      for (let key in data) {
        formdata.append(key, data[key])
      }
      requestData.data = formdata
    }
    // loading 效果
    let LoadName
    if (isLoading) {
      LoadName = ElLoading.service({
        lock: true,
        text: 'Loading',
        // spinner: 'el-icon-loading',
        background: 'rgba(255,255, 255, 0.7)',
      })
    }
    return Axios({
      method,
      url,
      ...requestData,
      ...config,
    })
      .then(res => {
        LoadName && LoadName.close()
        LoadName = null
        if (res.data.code === 0) {
          return Promise.resolve(res.data)
        } else {
          autoFileMag && ElMessage.error(res.data.message || this.fileMage)
          return Promise.reject(res.data)
        }
      })
      .catch(res => {
        LoadName && LoadName.close()
        LoadName = null
        if (res.code === undefined) {
          autoFileMag && ElMessage.error(res.message || this.fileMage)
        }
        return Promise.reject(res)
      })
  }
}

// 添加请求拦截器
Axios.interceptors.request.use(
  function (config) {
    // console.log('请求拦截', config)
    return config
  },
  function (error) {
    return Promise.reject(error)
  },
)

// 添加响应拦截器
Axios.interceptors.response.use(
  function (response) {
    // console.log('响应拦截', response)
    return response
  },
  function (error) {
    return Promise.reject(error)
  },
)

const _axios = new Http()

// Vue.use(Plugin)
export { _axios as axios }
export default _axios
